<template>
  <div class="table-structure-container">
    <!-- 新增全屏 loading 遮罩 -->
    <el-overlay v-if="isDetailLoading" class="fullscreen-loading">
      <div class="loading-content">
        <el-icon class="is-loading" style="font-size: 48px;"><Loading /></el-icon>
        <div style="margin-top: 16px; font-size: 18px; color: #409EFF;">加载中...</div>
      </div>
    </el-overlay>
    <div class="search-init-row" style="display: flex; align-items: center; margin-bottom: 20px; justify-content: center;">
      <!-- 搜索功能 -->
      <div style="display: flex; align-items: center; gap: 8px;">
        <el-input
          v-model="searchQuery"
          placeholder="请输入表名或表备注"
          class="search-input"
          style="width: 260px;"
          @keyup.enter="() => searchTable(1)"
          @input="handleSearchInput"
        />
        <el-button :loading="isSearching" @click="() => searchTable(1)">搜索</el-button>
      </div>

      <el-divider direction="vertical" style="height: 32px; margin: 0 24px;" />

      <!-- 初始化功能 -->
      <div style="display: flex; align-items: center; gap: 8px;">
        <el-input
          v-model="initSchema"
          placeholder="请输入数据库名(schema)"
          style="width: 234px;"
        />
        <el-input
          v-model="initTableName"
          placeholder="请输入表名"
          style="width: 234px;"
        />
        <el-button :loading="isInitializing" type="primary" @click="initTable">初始化</el-button>
      </div>
    </div>

    <!-- 搜索结果列表 -->
    <div v-if="hasSearched" class="search-results">
      <template v-if="meilisearchStructures.length > 0">
        <el-table :data="meilisearchStructures" style="width: 100%">
          <el-table-column prop="tableSchema" label="数据库" />
          <el-table-column prop="tableName" label="表名" />
          <el-table-column prop="tableComment" label="表注释" />
          <el-table-column label="操作" width="180">
            <template #default="scope">
              <el-button type="primary" size="small" @click="selectTable(scope.row)">查看详情</el-button>
              <el-button type="danger" size="small" @click="() => handleDeleteTable(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-buttons" style="margin-top: 16px; text-align: right;">
          <el-button
            size="small"
            :disabled="currentPage === 1 || isSearching"
            @click="goPrevPage"
          >上一页</el-button>
          <el-button
            size="small"
            :disabled="!hasNext || isSearching"
            @click="goNextPage"
          >下一页</el-button>
        </div>
      </template>
      <template v-else>
        <el-empty description="未找到匹配的表" />
      </template>
    </div>
    <div v-else class="search-results">
      <el-empty description="请搜索表名或表备注" />
    </div>

    <div class="table-section" v-if="selectedTable">
      <div class="structure-panel">
        <h3>Meilisearch表结构</h3>
        <div class="table-info">
          <p>数据库：{{ meilisearchStructure.tableSchema }}</p>
          <p>表名：{{ meilisearchStructure.tableName }}</p>
          <div class="table-comment">
            <span>表备注：</span>
            <el-input 
              v-model="meilisearchStructure.tableComment" 
              placeholder="请输入表备注"
              @change="saveMeilisearchTableComment"
            />
          </div>
        </div>
        <div class="column-list">
          <div v-for="column in mergedColumns" :key="column.columnName" class="column-item">
            <template v-if="!column.meilisearch.isPlaceholder">
              <el-input v-model="column.meilisearch.columnName" disabled />
              <el-input v-model="column.meilisearch.dataType" disabled />
              <el-input 
                v-model="column.meilisearch.columnComment" 
                placeholder="请输入字段注释" 
                @blur="() => handleMeilisearchCommentBlur(column.meilisearch)"
              />
              <el-tooltip
                content="同步"
                placement="right"
              >
                <el-button
                  v-if="needSync(column.meilisearch, 'meilisearch')" 
                  type="primary"
                  link
                  class="sync-button"
                  @click="syncComment(column.meilisearch, 'meilisearch')"
                >
                  <el-icon><ArrowRight /></el-icon>
                </el-button>
              </el-tooltip>
            </template>
            <template v-else>
              <div class="empty-column"></div>
              <div class="empty-column"></div>
              <div class="empty-column"></div>
              <div class="empty-column"></div>
            </template>
          </div>
        </div>
        <div class="actions">
          <el-button type="primary" @click="saveMeilisearchStructure">保存Meilisearch结构</el-button>
          <el-button type="success" class="sync-right-button" @click="batchSync('meilisearch')" :disabled="!databaseStructure.tableName">
            批量同步到MySQL
            <el-icon class="sync-icon"><ArrowRight /></el-icon>
          </el-button>
        </div>
      </div>

      <div class="structure-panel">
        <h3>数据库表结构</h3>
        <template v-if="databaseStructure && databaseStructure.tableName">
          <div class="table-info">
            <p>数据库：{{ databaseStructure.tableSchema }}</p>
            <p>表名：{{ databaseStructure.tableName }}</p>
            <div class="table-comment">
              <span>表备注：</span>
              <el-input 
                v-model="databaseStructure.tableComment" 
                placeholder="请输入表备注"
                @change="saveDatabaseTableComment"
              />
            </div>
          </div>
          <div class="column-list">
            <div v-for="column in mergedColumns" :key="column.columnName" class="column-item">
              <template v-if="!column.database.isPlaceholder">
                <div class="sync-button-wrapper">
                  <el-tooltip
                    content="同步"
                    placement="left"
                  >
                    <el-button
                      v-if="needSync(column.database, 'mysql')"
                      type="primary"
                      link
                      class="sync-button"
                      @click="syncComment(column.database, 'mysql')"
                    >
                      <el-icon><ArrowLeft /></el-icon>
                    </el-button>
                  </el-tooltip>
                </div>
                <el-input v-model="column.database.columnName" disabled />
                <el-input v-model="column.database.dataType" disabled />
                <el-input 
                  v-model="column.database.columnComment" 
                  placeholder="请输入字段注释" 
                  @change="() => onColumnCommentChange(column.database.columnName)"
                  @blur="() => handleMysqlCommentBlur(column.database)" 
                />
              </template>
              <template v-else>
                <div class="empty-column"></div>
                <div class="empty-column"></div>
                <div class="empty-column"></div>
                <div class="empty-column"></div>
              </template>
            </div>
          </div>
          <div class="actions">
            <el-button type="success" class="sync-left-button" @click="batchSync('mysql')">
              <el-icon class="sync-icon"><ArrowLeft /></el-icon>
              批量同步到Meilisearch
            </el-button>
            <el-button type="primary" @click="saveDatabaseComments">保存数据库注释</el-button>
          </div>
        </template>
        <template v-else>
          <el-empty description="未找到表结构" />
        </template>
      </div>
    </div>

    <!-- 添加底部保存按钮 -->
    <div v-if="selectedTable" class="save-all-section">
      <el-button 
        type="primary" 
        size="large"
        @click="handleSaveAll"
      >保存所有更改</el-button>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, ArrowRight, Loading } from '@element-plus/icons-vue'

export default {
  name: 'TableStructure',
  components: {
    ArrowLeft,
    ArrowRight,
    Loading
  },
  setup() {
    const searchQuery = ref('')
    const selectedTable = ref(null)
    const meilisearchStructures = ref([])
    const meilisearchStructure = ref({ 
      tableSchema: '',
      tableName: '',
      tableComment: '',
      columns: [] 
    })
    const databaseStructure = ref({ 
      tableSchema: '',
      tableName: '',
      tableComment: '',
      columns: [] 
    })
    const modifiedColumns = ref(new Set())
    const isSearching = ref(false)
    const hasSearched = ref(false)
    // 分页相关
    const currentPage = ref(1)
    const pageSize = ref(5)
    const hasNext = ref(false)
    const isDetailLoading = ref(false)
    // 初始化相关ref
    const initSchema = ref('')
    const initTableName = ref('')
    const isInitializing = ref(false)

    // 添加一个计算属性来获取合并后的字段列表
    const mergedColumns = computed(() => {
      const allColumnNames = new Set([
        ...meilisearchStructure.value.columns.map(col => col.columnName),
        ...databaseStructure.value.columns.map(col => col.columnName)
      ])
      
      const sortedColumnNames = Array.from(allColumnNames).sort()
      
      return sortedColumnNames.map(columnName => {
        const meilisearchColumn = meilisearchStructure.value.columns.find(col => col.columnName === columnName)
        const databaseColumn = databaseStructure.value.columns.find(col => col.columnName === columnName)
        return {
          columnName,
          meilisearch: meilisearchColumn || {
            columnName,
            dataType: '',
            columnComment: '',
            isPlaceholder: true
          },
          database: databaseColumn || {
            columnName,
            dataType: '',
            columnComment: '',
            isPlaceholder: true
          }
        }
      })
    })

    const handleSearchInput = () => {
      // 当输入新内容时，清除之前的搜索结果
      selectedTable.value = null
      meilisearchStructure.value = { 
        tableSchema: '',
        tableName: '',
        tableComment: '',
        columns: [] 
      }
      databaseStructure.value = { 
        tableSchema: '',
        tableName: '',
        tableComment: '',
        columns: [] 
      }
    }

    const searchTable = async (page = 1) => {
      if (!searchQuery.value.trim()) {
        ElMessage.warning('请输入搜索内容')
        return
      }
      isSearching.value = true
      hasSearched.value = true
      currentPage.value = page
      try {
        const response = await axios.get(`/api/doris/table-structure/meilisearch/${searchQuery.value}`, {
          params: { page: currentPage.value, size: pageSize.value }
        })
        meilisearchStructures.value = response.data.data
        hasNext.value = response.data.hasNext
      } catch (error) {
        console.error('搜索表结构失败:', error)
        ElMessage.error('搜索失败')
        meilisearchStructures.value = []
        hasNext.value = false
      } finally {
        isSearching.value = false
      }
    }

    const selectTable = (table) => {
      selectedTable.value = table.tableName
      meilisearchStructure.value = table
      isDetailLoading.value = true // 开始 loading
      loadDatabaseStructure(table.tableName, table.tableSchema)
    }

    const loadDatabaseStructure = async (tableName, tableSchema) => {
      try {
        const response = await axios.get(`/api/doris/table-structure/database/${tableSchema}/${tableName}`)
        const data = response.data
        if (!data || Object.keys(data).length === 0) {
          databaseStructure.value = { tableSchema: '', tableName: '', tableComment: '', columns: [] }
        } else {
          databaseStructure.value = data
        }
      } catch (error) {
        console.error('加载数据库表结构失败:', error)
        ElMessage.error('加载失败')
      } finally {
        isDetailLoading.value = false // 无论成功失败都关闭 loading
      }
    }

    const saveMeilisearchStructure = async () => {
      try {
        await axios.put('/api/doris/table-structure/meilisearch/structure', meilisearchStructure.value)
        ElMessage.success('Meilisearch结构保存成功')
      } catch (error) {
        console.error('保存Meilisearch结构失败:', error)
        ElMessage.error('保存失败')
      }
    }

    const onColumnCommentChange = (columnName) => {
      modifiedColumns.value.add(columnName)
    }

    const saveDatabaseComments = async () => {
      try {
        if (modifiedColumns.value.size === 0) {
          ElMessage.warning('没有字段被修改')
          return
        }

        const modifiedData = {
          tableSchema: databaseStructure.value.tableSchema,
          tableName: databaseStructure.value.tableName,
          columns: databaseStructure.value.columns.filter(col => 
            modifiedColumns.value.has(col.columnName)
          )
        }

        await axios.put('/api/doris/table-structure/database/comment', modifiedData)
        ElMessage.success('数据库注释保存成功')
        modifiedColumns.value.clear()
      } catch (error) {
        console.error('保存数据库注释失败:', error)
        ElMessage.error(error.response?.data || '保存失败')
      }
    }

    const saveMeilisearchTableComment = async () => {
      try {
        await axios.put('/api/doris/table-structure/meilisearch/table-comment', {
          id: meilisearchStructure.value.id,
          tableComment: meilisearchStructure.value.tableComment
        })
        ElMessage.success('Meilisearch表备注保存成功')
      } catch (error) {
        console.error('保存Meilisearch表备注失败:', error)
        ElMessage.error(error.response?.data || '保存失败')
      }
    }

    const saveDatabaseTableComment = async () => {
      try {
        await axios.put('/api/doris/table-structure/database/table-comment', {
          tableSchema: databaseStructure.value.tableSchema,
          tableName: databaseStructure.value.tableName,
          tableComment: databaseStructure.value.tableComment
        })
        ElMessage.success('数据库表备注保存成功')
      } catch (error) {
        console.error('保存数据库表备注失败:', error)
        ElMessage.error(error.response?.data || '保存失败')
      }
    }

    // 判断是否需要同步
    const needSync = (column, source) => {
      const targetColumns = source === 'meilisearch' 
        ? databaseStructure.value.columns 
        : meilisearchStructure.value.columns
      
      const targetColumn = targetColumns.find(c => c.columnName === column.columnName)
      return targetColumn && targetColumn.columnComment !== column.columnComment
    }

    // 同步单个字段的注释
    const syncComment = (column, source) => {
      const targetColumns = source === 'meilisearch' 
        ? databaseStructure.value.columns 
        : meilisearchStructure.value.columns
      
      const targetColumn = targetColumns.find(c => c.columnName === column.columnName)
      if (targetColumn) {
        const oldComment = targetColumn.columnComment
        targetColumn.columnComment = column.columnComment
        
        // 如果是从 Meilisearch 同步到 MySQL
        if (source === 'meilisearch') {
          modifiedColumns.value.add(targetColumn.columnName)
        }
        
        ElMessage.success(`字段 ${column.columnName} 的注释已同步，需手动保存`)
      }
    }

    // 批量同步所有需要同步的字段
    const batchSync = (source) => {
      const sourceColumns = source === 'meilisearch' 
        ? meilisearchStructure.value.columns 
        : databaseStructure.value.columns
      
      let syncCount = 0
      sourceColumns.forEach(column => {
        if (needSync(column, source)) {
          const targetColumns = source === 'meilisearch' 
            ? databaseStructure.value.columns 
            : meilisearchStructure.value.columns
          
          const targetColumn = targetColumns.find(c => c.columnName === column.columnName)
          if (targetColumn) {
            const oldComment = targetColumn.columnComment
            targetColumn.columnComment = column.columnComment
            
            // 如果是从 Meilisearch 同步到 MySQL
            if (source === 'meilisearch') {
              modifiedColumns.value.add(targetColumn.columnName)
            }
            
            syncCount++
          }
        }
      })
      
      if (syncCount > 0) {
        ElMessage.success(`已同步 ${syncCount} 个字段的注释，需手动保存`)
      } else {
        ElMessage.info('没有需要同步的字段')
      }
    }

    const handleMeilisearchCommentBlur = async (column) => {
      if (needSync(column, 'meilisearch')) {
        try {
          const result = await ElMessageBox.confirm(
            '检测到字段备注有变更，是否同步到MySQL？',
            '同步确认',
            {
              confirmButtonText: '同步',
              cancelButtonText: '不同步',
              type: 'info'
            }
          )
          if (result === 'confirm') {
            syncComment(column, 'meilisearch')
          }
        } catch (error) {
          // 用户点击不同步，不做任何操作
        }
      }
    }

    const handleMysqlCommentBlur = async (column) => {
      if (needSync(column, 'mysql')) {
        try {
          const result = await ElMessageBox.confirm(
            '检测到字段备注有变更，是否同步到Meilisearch？',
            '同步确认',
            {
              confirmButtonText: '同步',
              cancelButtonText: '不同步',
              type: 'info'
            }
          )
          if (result === 'confirm') {
            syncComment(column, 'mysql')
          }
        } catch (error) {
          // 用户点击不同步，不做任何操作
        }
      }
    }

    const handleSaveAll = async () => {
      try {
        const result = await ElMessageBox.confirm(
          'meilisearch和数据库注释中修改的备注信息都将被保存，是否继续？',
          '保存确认',
          {
            confirmButtonText: '继续',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        if (result === 'confirm') {
          // 保存 Meilisearch 结构
          await saveMeilisearchStructure()
          
          // 保存 MySQL 结构（如果有修改的话）
          if (modifiedColumns.value.size > 0) {
            await saveDatabaseComments()
          }
          
          ElMessage.success('所有更改已保存成功')
        }
      } catch (error) {
        if (error === 'cancel') {
          // 用户点击取消，不做任何操作
          return
        }
        console.error('保存所有更改失败:', error)
        ElMessage.error('保存失败')
      }
    }

    const goPrevPage = () => {
      if (currentPage.value > 1) {
        searchTable(currentPage.value - 1)
      }
    }

    const goNextPage = () => {
      if (hasNext.value) {
        searchTable(currentPage.value + 1)
      }
    }

    const handleDeleteTable = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除表【${row.tableName}】吗？此操作不可恢复！`,
          '删除确认',
          {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        await axios.delete(`/api/doris/table-structure/meilisearch/${row.id}`)
        ElMessage.success('删除成功')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error(error.response?.data || '删除失败')
        }
      } finally {
        // 删除后无论成功与否都刷新列表
        searchTable(1)
      }
    }

    // 初始化方法
    const initTable = async () => {
      if (!initSchema.value.trim() || !initTableName.value.trim()) {
        ElMessage.warning('请输入数据库名和表名')
        return
      }
      isInitializing.value = true
      try {
        const res = await axios.post('/api/doris/table-structure/init', {
          tableSchema: initSchema.value.trim(),
          tableName: initTableName.value.trim()
        })
        if (res.data && (res.data.success === true || res.data.code === 0)) {
          ElMessage.success('初始化成功')
        } else if (res.data && res.data.message) {
          ElMessage.error(res.data.message)
        } else {
          ElMessage.error('初始化失败')
        }
      } catch (e) {
        if (e.response && e.response.data && e.response.data.message) {
          ElMessage.error(e.response.data.message)
        } else {
          ElMessage.error('初始化失败，表不存在或服务异常')
        }
      } finally {
        isInitializing.value = false
        // 初始化后无论成功与否都刷新列表，回到第一页
        searchTable(1)
      }
    }

    return {
      searchQuery,
      selectedTable,
      meilisearchStructures,
      meilisearchStructure,
      databaseStructure,
      mergedColumns,
      isSearching,
      hasSearched,
      searchTable,
      handleSearchInput,
      selectTable,
      saveMeilisearchStructure,
      saveDatabaseComments,
      onColumnCommentChange,
      saveMeilisearchTableComment,
      saveDatabaseTableComment,
      needSync,
      syncComment,
      batchSync,
      handleMeilisearchCommentBlur,
      handleMysqlCommentBlur,
      handleSaveAll,
      // 分页相关
      currentPage,
      pageSize,
      hasNext,
      goPrevPage,
      goNextPage,
      isDetailLoading,
      handleDeleteTable,
      initSchema,
      initTableName,
      isInitializing,
      initTable
    }
  }
}
</script>

<style scoped>
.table-structure-container {
  padding: 20px;
  width: 100%;
}

.search-init-row {
  margin-bottom: 20px;
}

.search-input {
  width: 400px;
}

.search-results {
  margin-bottom: 20px;
}

.table-section {
  display: flex;
  gap: 20px;
}

.structure-panel {
  flex: 1;
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.table-info {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.table-info p {
  margin: 5px 0;
}

.column-list {
  margin-bottom: 20px;
}

/* 左侧 Meilisearch 表格样式 */
.structure-panel:first-child .column-item {
  display: grid;
  grid-template-columns: 2fr 2fr 3fr 32px;
  gap: 10px;
  margin-bottom: 10px;
  align-items: center;
  min-height: 32px; /* 确保空行也有一定的高度 */
}

/* 右侧 MySQL 表格样式 */
.structure-panel:last-child .column-item {
  display: grid;
  grid-template-columns: 32px 2fr 2fr 3fr;
  gap: 10px;
  margin-bottom: 10px;
  align-items: center;
  min-height: 32px; /* 确保空行也有一定的高度 */
}

.sync-button {
  padding: 2px;
  height: 24px;
  width: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
}

.sync-button:hover {
  background-color: var(--el-color-primary-light-9);
}

.sync-button .el-icon {
  font-size: 14px;
  color: var(--el-color-primary);
}

:deep(.el-tooltip__trigger) {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
}

:deep(.el-tooltip__popper) {
  font-size: 12px;
  padding: 4px 8px;
  border-radius: 4px;
}

.actions {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  padding: 0 10px;
}

.sync-icon {
  margin: 0 4px;
}

.sync-right-button {
  display: flex;
  align-items: center;
}

.sync-left-button {
  display: flex;
  align-items: center;
}

.table-comment {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 5px 0;
}

.table-comment span {
  white-space: nowrap;
}

.table-comment .el-input {
  flex: 1;
}

.sync-button-wrapper {
  width: 32px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.save-all-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 20px;
  border-top: 1px solid #dcdfe6;
}

.save-all-section .el-button {
  min-width: 200px;
}

.empty-column {
  height: 32px; /* 与el-input的默认高度保持一致 */
  background-color: #f5f7fa;
  border-radius: 4px;
  opacity: 0.5;
}

.fullscreen-loading {
  position: fixed;
  z-index: 9999;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(255,255,255,0.7);
  display: flex;
  align-items: center;
  justify-content: center;
}
.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style> 